﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Newtonsoft.Json;

namespace Microsoft.Extensions.Localization {
    public class JsonStringLocalizer:IStringLocalizer {
        List<JsonLocalizationFile> localization = new List<JsonLocalizationFile>();
        public JsonStringLocalizer() {
            //read all json file
            JsonSerializer serializer = new JsonSerializer();
            localization = JsonConvert.DeserializeObject<List<JsonLocalizationFile>>(File.ReadAllText(@"zh-CN.json"));
        }
        public LocalizedString this[string name] {
            get {
                var value = GetString(name);
                return new LocalizedString(name,value ?? name,resourceNotFound: value == null);
            }
        }
        public LocalizedString this[string name,params object[] arguments] {
            get {
                var format = GetString(name);
                var value = string.Format(format ?? name,arguments);
                return new LocalizedString(name,value,resourceNotFound: format == null);
            }
        }

        public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures) {
            return localization.Where(l => l.Texts.Keys.Any(lv => lv == CultureInfo.CurrentCulture.Name)).Select(l => new LocalizedString(l.Culture,l.Texts[CultureInfo.CurrentCulture.Name],true));
        }

        public IStringLocalizer WithCulture(CultureInfo culture) {
            return new JsonStringLocalizer();
        }

        private string GetString(string culture) {
            var query = localization.Where(l => l.Texts.Keys.Any(lv => lv == CultureInfo.CurrentCulture.Name));
            var value = query.FirstOrDefault(l => l.Culture == culture);
            return value.Texts[CultureInfo.CurrentCulture.Name];
        }
    }
}
